package com.jijs.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.jijs.bean.User;
import com.jijs.exception.UserException;

public class UserDAO {

	private static final Map<String, User> users = new HashMap<String, User>();
	private static UserDAO userDAO = null;

	private UserDAO() {
		User user = new User();
		user.setNickname("管理员");
		user.setPassword("123");
		user.setUsername("admin");
		users.put("admin", user);
	}

	public static UserDAO getInstance() {
		if (userDAO == null) {
			userDAO = new UserDAO();
		}
		return userDAO;
	}

	public void add(User user) throws UserException {
		System.out.println("---------"+user.getUsername());
		if (users.containsKey(user.getUsername())) {
			throw new UserException("用户已经存在了-");
		}
		users.put(user.getUsername(), user);
	}

	public void delete(String username) {
		users.remove(username);
	}

	public List<User> list() {
		Set<String> keys = users.keySet();
		List<User> list = new ArrayList<User>();
		for (String key : keys) {
			list.add(users.get(key));
		}
		return list;
	}

	public User login(String username, String password) throws UserException {
		if (!users.containsKey(username)) {
			throw new UserException("用户不存在");
		}
		User u = users.get(username);
		if (!password.equals(u.getPassword())) {
			throw new UserException("用户密码不正确!");
		}
		return u;
	}
}
